package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Role;
import priv.mill.server.RoleService;

@Controller
@RequestMapping("Role")
public class RoleController {

	@Autowired
	private RoleService roleService;

	private static final Logger logger = Logger.getLogger(RoleController.class);

	@RequestMapping("getRoleById")
	@ResponseBody
	public RetenObj getRoleById(@RequestParam("RoleId") Integer roleId) {
		try {
			return warpData(roleService.getRoleById(roleId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getRoleByEntry")
	@ResponseBody
	public RetenObj getRoleByEntry(Role role) {
		try {
			return warpData(roleService.getRoleByEntry(role), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getRolesByPage")
	@ResponseBody
	public RetenObj getRolesByPage(Role role) {
		try {
			return warpData(roleService.getRolesByPage(role), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateRole")
	@ResponseBody
	public RetenObj updateRole(Role role) {
		try {
			int result = roleService.updateRole(role);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertRole")
	@ResponseBody
	public RetenObj insertRole(Role role) {
		try {
			int result = roleService.insertRole(role);
			if (result > 0)
				return warpData(role.getRoleId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteRole")
	
	@ResponseBody
	public RetenObj deleteRole(Integer roleId) {
		try {
			int result = roleService.deleteRole(roleId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
